package com.holystone.orca.itsm.controller;

import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/")
public class ShiroController {

    @ResponseBody
    @RequestMapping(value = "login"/*, method = RequestMethod.POST*/)
    public Map<String, Object> userLogin(String username, String password, Boolean rememberMe) {
        Map<String, Object> map = new HashMap<>();
        // 加密方法(md5, SHA-1, SHA-256, SHA-512 等等)，“密码明文”,"盐值" hash次数
        SimpleHash sh = new SimpleHash("MD5", password, username, 1024);
        System.out.println("加密后:" + sh);
        rememberMe = rememberMe == null ? false : rememberMe;
        // 1、 封装用户名、密码、是否记住我到token令牌对象  [支持记住我]
        UsernamePasswordToken usertoken = new UsernamePasswordToken(username, sh.toString(), rememberMe);
        Subject subject = SecurityUtils.getSubject();
        JSONObject data = new JSONObject();
        data.put("token",subject.getSession().getId());
        try {
            subject.login(usertoken);
            map.put("data",data);
            map.put("code", 200);
            map.put("msg", "登录成功！");
            map.put("username", username);
        } catch (Exception e) {
            map.put("code", 500);
            map.put("msg", e.getMessage());
        }
        return map;
    }


}